package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.user.JwtUtils.JwtUtils;
import com.itheima.user.domain.po.User;
import com.itheima.user.mapper.UserMapper;
import com.itheima.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(String phone, String pwd) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getPhone, phone).eq(User::getPwd, pwd);

        String token = null;
        User user = userMapper.selectOne(wrapper);
        if (ObjectUtils.isNotNull(user)){
            Map<String,Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("name", user.getName());
            token = JwtUtils.generateToken(map);
        }
        return token;
    }

    @Override
    public void register(User user) {
        userMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public User getUser(Long id) {
        User user = userMapper.selectById(id);
        return user;
    }
}
